package com.mytijian.code.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mytijian.code.enums.SendCodeStatusEnum;
import com.mytijian.code.exceptions.MashangExceptionEnum;
import com.mytijian.code.model.MerchantOrder;
import com.mytijian.exception.BizException;

@Service("merchantOrderSendCodeLifeCycle")
public class MerchantOrderSendCodeLifeCycleImpl implements MerchantOrderSendCodeLifeCycle {
	
	private Logger logger = LoggerFactory.getLogger(MerchantOrderSendCodeLifeCycleImpl.class);

	@Autowired
	private MerchantOrderService merchantOrderService;

	@Override
	public void finishSendCode(Integer merchantOrderId, Integer oldSendCodeStatus) {
		int updateRowNum = updateSendCodeStatus(merchantOrderId, SendCodeStatusEnum.SEND, oldSendCodeStatus);
		if (updateRowNum == 0) {
			logger.info("订单id={}重复发码，原发码状态status={}", merchantOrderId, oldSendCodeStatus);
			throw new BizException(MashangExceptionEnum.REPETITION_SEND_CODE);
		}
	}

	@Override
	public void unResendCode(Integer merchantOrderId) {
		updateSendCodeStatus(merchantOrderId, SendCodeStatusEnum.UN_RESEND);
	}

	@Override
	public void finishResendCode(Integer merchantOrderId) {
		updateSendCodeStatus(merchantOrderId, SendCodeStatusEnum.RESEND);
	}

	private void updateSendCodeStatus(Integer merchantOrderId, SendCodeStatusEnum sendCodeStatus) {
		updateSendCodeStatus(merchantOrderId, sendCodeStatus, null);
	}

	private int updateSendCodeStatus(Integer merchantOrderId, SendCodeStatusEnum sendCodeStatus,
			Integer oldSendCodeStatus) {
		MerchantOrder order = new MerchantOrder();
		order.setId(merchantOrderId);
		order.setSendCodeStatus(sendCodeStatus.getCode());
		return merchantOrderService.updateTmOrder(order, oldSendCodeStatus);
	}

}
